<template>
  <div style="position: relative">
    <Spin :withIcon="true" v-if="loading"></Spin>
    <div class="listTable-area flx-row-s-c" style="padding-left: 34px">
      <div
        class="flx-row-s-c"
        v-for="(item, index) in processList"
        :key="index"
      >
        <div class="step-item" :class="[index < active ? 'b-arrow' : '']">
          {{ item }}
        </div>
        <div class="next-icon" v-if="index != 3"></div>
      </div>
    </div>
    <template v-if="active == 1">
      <div class="listTable-area">
        <div class="filter-line flx-row-s-c">
          <span class="item-name">类型</span>
          <Select v-model="typeSelect" style="width: 150px">
            <Option
              v-for="item in typeList"
              :value="item.type"
              :key="item.type"
              >{{ item.name }}</Option
            >
          </Select>
          <span class="item-name">交易时间</span>
          <DatePicker
            :editable="false"
            type="daterange"
            split-panels
            clearable
            placeholder="请选择"
            style="width: 210px"
            @on-change="dateChange"
            :value="time"
          ></DatePicker>
          <span class="item-name">可开票金额</span>
          <Input
            v-model.trim="startAmount"
            number
            placeholder=""
            maxlength="10"
            type="number"
            style="width: 100px"
          />
          <div class="two-input-middle"></div>
          <Input
            v-model.trim="endAmount"
            number
            placeholder=""
            type="number"
            maxlength="10"
            style="width: 100px"
          />
          <div
            class="user-strong-button line-button-size"
            style="margin: 0 10px 0 30px"
            @click="pageChange(1)"
          >
            搜索
          </div>
          <div class="user-normal-button line-button-size" @click="reset">
            重置
          </div>
        </div>
      </div>
      <div class="listTable-area">
        <div class="filter-line b-b-d flx-row-s-c" style="margin-top: -15px">
          <div class="flx-row-s-c f-14">
            <span class="name">本月可开票金额：</span>
            <span class="c-green">￥{{ invoicingTotal }}</span>
          </div>
          <div class="flx-row-s-c f-14">
            <span class="name c-d2">可开票总金额：</span>
            <span class="c-green">￥{{ invoicetotal }}</span>
          </div>
          <div class="flx-row-s-c f-14">
            <span class="name">已开票总金额:</span>
            <span class="c-green">￥{{ invoicedTotal }}</span>
          </div>
        </div>

        <div class="filter-line flx-row-s-c">
          <div class="flx-row-s-c f-14">
            <span class="name c-d2">已选开票金额:</span>
            <span class="c-o">￥{{ selectTotal }}</span>
          </div>
          <div
            class="user-strong-button small-button-size pub-m-l-47"
            @click="toApply"
          >
            申请发票
          </div>
        </div>
      </div>

      <div class="listTable-area pub-p-b-1">
        <div class="filter-line search-result-line flx-row-bw-c">
          <div class="flx-row-s-c pub-m-l-10">
            <span
              v-for="(item, index) in filterList"
              :key="index"
              class="select-item"
              :class="[index == filterActive ? 'active' : 'normal']"
              style="margin-right: 40px"
              @click="filterSelect(index)"
            >
              {{ item.name }}
            </span>
          </div>
        </div>
        <div class="my-domain-table">
          <Table
            :loading="loading"
            ref="pushDomianTable"
            :columns="columns"
            :data="list"
            :disabled-hover="true"
            @on-select="onSelectEvent"
            @on-select-cancel="onSelectCancelEvent"
            @on-select-all="onSelectAllEvent"
            @on-select-all-cancel="onSelectAllCancelEvent"
            stripe
          ></Table>
          <div class="form-page-bottom-area flx-row-c-c">
            <Page
              :total="total"
              :current="page"
              :page-size="pageSize"
              :page-size-opts="pageSizeOpts"
              @on-change="pageChange"
              @on-page-size-change="pageSizeChange"
              show-elevator
              show-sizer
              show-total
            />
          </div>
        </div>
      </div>
    </template>

    <template v-else-if="active == 2">
      <div class="listTable-area">
        <div class="filter-line flx-row-s-c pub-p-l-40">
          <span class="f-14 c-black">
            <span
              >您选取了<span class="c-o"> {{ selectList.length }} </span
              >条单据开具发票</span
            >
            <span>（若选中多条记录，金额将合并开具在一张票据中）</span>
          </span>
          <span class="c-black" style="margin-left: 40px"
            >已选开票金额：<span class="c-o">￥{{ selectTotal }}</span></span
          >
        </div>
        <div class="form-input-area" style="position: relative">
          <Spin :withIcon="true" v-if="loading"></Spin>
          <div class="flx-row-s-c div-line">
            <div class="long-name">发票信息</div>
            <Select
              v-model="infoId"
              filterable
              style="width: 250px"
              placeholder="请选择"
              @on-change="infoChange"
            >
              <Option
                v-for="item in infoList"
                :value="item.id"
                :key="item.id"
                >{{
                  `${item.header} - ${
                    item.issuingType == 0 ? "个人" : "类型"
                  } - ${
                    item.invoiceType == 0 ? "增值税普通发票" : "增值税专用发票"
                  }`
                }}</Option
              >
            </Select>
            <div
              class="form-font-button f-w-600"
              style="margin-left: 20px"
              @click="invoiceInfoModalShow = true"
            >
              +发票信息
            </div>
          </div>
          <template v-if="infoId != null">
            <div class="flx-row-s-c div-line">
              <div class="long-name">开具类型</div>
              <RadioGroup :value="invoiceInfoType.issuingType">
                <Radio class="radio-mg-r-20" :label="0" disabled>个人</Radio>
                <Radio class="radio-mg-r-20" :label="1" disabled>企业</Radio>
              </RadioGroup>
            </div>
            <div class="flx-row-s-c div-line">
              <div class="long-name">发票类型</div>
              <RadioGroup :value="invoiceInfoType.invoiceType">
                <Radio class="radio-mg-r-20" :label="0" disabled
                  >增值税普通发票</Radio
                >
                <Radio class="radio-mg-r-20" :label="1" disabled
                  >增值税专用发票</Radio
                >
              </RadioGroup>
            </div>
            <div class="flx-row-s-c div-line">
              <div class="long-name">发票抬头</div>
              <span class="c-d2">{{ header }}</span>
            </div>
          </template>
          <div class="flx-row-s-c div-line long-name-nece">
            <div class="long-name">发票内容</div>
            <RadioGroup v-model="contentType">
              <Radio class="radio-mg-r-20" :label="0">域名服务费</Radio>
              <Radio class="radio-mg-r-20" :label="1">信息服务费</Radio>
            </RadioGroup>
          </div>
          <div class="flx-row-s-c div-line long-name-nece">
            <div class="long-name">收件人</div>
            <Input
              v-model.trim="consignee"
              placeholder=""
              maxlength="15"
              style="width: 200px"
            />
          </div>
          <div class="flx-row-s-c div-line long-name-nece">
            <div class="long-name">手机号码</div>
            <Input
              v-model.trim="mobile"
              placeholder=""
              maxlength="11"
              style="width: 200px"
            />
          </div>
          <div class="flx-row-s-c div-line">
            <div class="flx-row-s-c long-name-nece">
              <div class="long-name">收件人地址</div>
              <Input
                v-model.trim="address"
                placeholder="请如实境写你的收件地址"
                maxlength="50"
                style="width: 300px"
              />
            </div>

            <span class="c-g" style="margin-left: 15px"
              >如：xx省xxx市xx县(区)xx路(街道)xx号</span
            >
          </div>
          <div class="flx-row-s-c div-line">
            <div class="long-name">邮箱</div>
            <Input
              v-model.trim="postalCode"
              placeholder=""
              maxlength="30"
              style="width: 200px"
            />
          </div>
          <div class="flx-row-s-c div-line">
            <div class="long-name">备注</div>
            <Input
              v-model.trim="remark"
              placeholder=""
              maxlength="30"
              style="width: 300px"
            />
          </div>
          <div class="submit-button-style-first div-line flx-row-s-c">
            <RadioGroup v-model="expressType">
              <Radio
                class="radio-mg-r-20"
                :label="0"
                :disabled="
                  expressFee == null ||
                  expressFee == '' ||
                  $store.state.user.balance < expressFee
                "
                ><span class="c-d2"
                  >快递<span class="c-o">{{ expressFee }}</span
                  >元（当前可用余额：{{ $store.state.user.balance }}元)</span
                ></Radio
              >
              <Radio class="radio-mg-r-20" :label="1"
                ><span class="c-d2">到付（顺丰）</span></Radio
              >
            </RadioGroup>
          </div>
          <div class="submit-button-style-first div-line flx-row-s-c">
            <Checkbox style="c-d2" v-model="isDefault">设置默认信息</Checkbox>
          </div>
          <div class="flx-row-s-c">
            <div
              class="
                user-strong-button
                submit-button-style submit-button-style-first
              "
              @click="submit"
            >
              申请发票
            </div>
            <div
              class="user-normal-button submit-button-style"
              style="margin: 0 34px 0 23px"
              @click="goback"
            >
              返回上一步
            </div>
          </div>
          <invoice-info-modal
            :show.sync="invoiceInfoModalShow"
            :type="1"
            @submit-success="getAllInvoiceInfoList"
          ></invoice-info-modal>
        </div>
      </div>
    </template>
  </div>
</template>

<script>
import { invoiceType } from "@/utils/publicData";
import {
  getInvoiceAmountTotal,
  getInvoiceAmountList,
  getAllInvoiceInfoList,
  getDefaultInfo,
  applyInvoice,
} from "@/api/user";
import Tools from "@/utils/tools";
export default {
  name: "VipInvoiceApply",
  components: {
    invoiceInfoModal: () =>
      import("_c/modal/userModal/invoiceInfoModal/invoiceInfoModal"),
  },
  data() {
    return {
      loading: false,
      test: "",
      typeList: [],
      typeSelect: null,
      time: [],
      startTime: "",
      endTime: "",
      startAmount: "",
      endAmount: "",
      processList: [
        "1、选择开票订单",
        "2、填写发票信息和地址",
        "3、后台审核，邮件发票",
        "4、签收快递，开票成功",
      ],
      columns: [
        {
          width: 60,
          type: "selection",
         align: "center",
        },
        {
          title: "交易时间",
          key: "createdTime",
         align: "left",
        },
        {
          title: "类型",
          key: "typeName",
         align: "left",
        },
        {
          title: "交易金额",
          key: "payable",
         align: "left",
        },
        {
          title: "可开票金额",
          key: "amount",
         align: "left",
        },
        {
          minWidth: 250,
          title: "备注",
          key: "remark",
         align: "left",
        },
      ],
      // 保存选中的数据
      selectList: [],
      // 分页设置
      total: null,
      pageSizeOpts: [50, 100, 200],
      pageSize: 50,
      page: 1,
      list: [],

      active: 1,
      filterList: [
        {
          name: "本月可开",
          value: 0,
        },
        {
          name: "下月可开",
          value: 1,
        },
        {
          name: "已开票记录",
          value: 2,
        },
      ],
      filterActive: 0,

      invoicedTotal: "",
      invoicingTotal: "",
      invoicetotal: "",

      // 申请数据
      infoList: [],
      infoId: null,
      header: "",
      contentType: 0,
      consignee: "",
      mobile: "",
      address: "",
      postalCode: "",
      remark: "",
      expressType: null,
      expressFee: "",
      isDefault: false,

      invoiceInfoModalShow: false,
    };
  },
  created() {
    this.invoiceTypeList();
    this.getInvoiceAmountTotal();
    this.getList();
  },
  methods: {
    // 获取发票信息列表
    async getAllInvoiceInfoList() {
      let res = await getAllInvoiceInfoList();
      if (res.code == 200) {
        this.infoList = res.data;
      }
    },
    // 获取发票类型
    async invoiceTypeList() {
      let list = await invoiceType();
      this.typeList = list;
    },
    // 获取发票金额数据
    async getInvoiceAmountTotal() {
      let res = await getInvoiceAmountTotal();
      if (res.code == 200) {
        this.invoicedTotal = res.data.invoicedTotal;
        this.invoicingTotal = res.data.invoicingTotal;
        this.invoicetotal = res.data.total;
      }
    },
    // 日期选择改变
    dateChange(date) {
      this.startTime = date[0];
      this.endTime = date[1];
    },
    // 时间类型选择改变
    filterSelect(index) {
      this.filterActive = index;
      this.pageChange(1);
    },
    // 获取列表
    async getList() {
      if (this.startAmount || this.endAmount) {
        if (
          !(
            this.startAmount &&
            this.endAmount &&
            this.startAmount > 0 &&
            this.endAmount > 0 &&
            this.startAmount < this.endAmount
          )
        ) {
          this.$Message.warning("请确认可开票金额是否输入错误！");
          return;
        }
      }
      this.loading = true;
      let params = {
        type: this.typeSelect,
        startTime: this.startTime,
        endTime: this.endTime,
        limit: this.pageSize,
        page: this.page,
        timeType: this.filterActive,
      };
      if (this.startAmount && this.endAmount) {
        params.startAmount = this.startAmount;
        params.endAmount = this.endAmount;
      }
      let res = await getInvoiceAmountList(params);
      if (res.code == 200) {
        if (this.filterActive != 0) {
          this.list = res.data.list.map((item) => {
            return {
              ...item,
              _disabled: true,
            };
          });
        } else {
          this.list = res.data.list;
        }
        this.total = res.data.total;
      }
      this.loading = false;
    },
    // 切换pageSize
    pageSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.pageChange(1);
    },
    // 切换页码
    pageChange(page) {
      this.page = page;
      this.getList();
    },
    // 重置
    reset() {
      this.typeSelect = null;
      this.time = [];
      this.startTime = "";
      this.endTime = "";
      this.startAmount = "";
      this.endAmount = "";
      this.page = 1;
      this.getList();
    },
    // checkbox单个选中数据
    onSelectEvent(selection, row) {
      this.selectList.push(row);
    },
    // checkbox单个取消数据
    onSelectCancelEvent(selection, row) {
      this.selectList.splice(
        this.selectList.findIndex((item) => item.id === row.id),
        1
      );
    },
    // checkbox全选的数据
    onSelectAllEvent(selection) {
      this.selectList = selection;
    },
    // checkbox取消全选的数据
    onSelectAllCancelEvent() {
      this.selectList = [];
    },
    // 去开发票
    toApply() {
      if (!this.selectList || this.selectList.length <= 0) {
        this.$Message.warning("您未选择任何可开发票！");
        return;
      }
      this.getAllInvoiceInfoList();
      this.getDefaultInfo();
      this.active = 2;
    },
    // 发票信息选择改变
    infoChange() {
      for (let i in this.infoList) {
        if (this.infoList[i].id == this.infoId) {
          this.header = this.infoList[i].header;
          return;
        }
      }
    },
    // 提交申请
    async submit() {
      if (this.selectList.length <= 0) {
        this.$Message.warning("请选择开票订单！");
        this.active = 1;
        this.clearAll();
        return;
      }
      if (!this.infoId) {
        this.$Message.warning("请输入选择发票信息！");
        return;
      }
      if (this.consignee == null || this.consignee == "") {
        this.$Message.warning("请输入收件人！");
        return;
      }
      if (this.mobile == null || this.mobile == "") {
        this.$Message.warning("请输入手机号码！");
        return;
      }
      if (this.address == null || this.address == "") {
        this.$Message.warning("请输入手机号码！");
        return;
      }
      if (this.expressType == null) {
        this.$Message.warning("请选择支付方式！");
        return;
      }
      this.loading = true;
      let data = {
        ids: this.selectList.map((item) => item.id),
        infoId: this.infoId,
        header: this.header,
        contentType: this.contentType,
        consignee: this.consignee,
        mobile: this.mobile,
        address: this.address,
        postalCode: this.postalCode,
        remark: this.remark,
        expressType: this.expressType,
        isDefault: this.isDefault ? 1 : 0,
      };
      let res = await applyInvoice(data);
      if (res.code == 200) {
        this.$Message.success("申请提交成功，您的申请将在后台审核！");
        if (res.data != null) {
          this.$store.commit("setBalance", res.data);
        }
        this.clearAll();
        this.selectList = [];
        this.active = 1;
        this.pageChange(1);
      }
      this.loading = false;
    },
    // 获取申请发票默认信息
    async getDefaultInfo() {
      let res = await getDefaultInfo();
      if (res.code == 200 && res.data != null) {
        if (res.data.infoId) {
          this.infoId = res.data.infoId;
          this.header = res.data.header;
          this.contentType = res.data.contentType;
          this.consignee = res.data.consignee;
          this.mobile = res.data.mobile;
          this.address = res.data.address;
          this.postalCode = res.data.postalCode;
        }
        this.expressFee = res.data.expressFee;
      }
    },
    // 清空选项
    clearAll() {
      this.infoId = null;
      this.header = "";
      this.contentType = 0;
      this.consignee = "";
      this.mobile = "";
      this.address = "";
      this.postalCode = "";
      this.remark = "";
      this.expressType = null;
      this.isDefault = false;
    },
    // 返回上一步
    goback() {
      this.clearAll();
      this.selectList = [];
      this.active = 1;
    },
  },
  computed: {
    selectTotal() {
      let total = 0;
      if (this.selectList.length > 0) {
        this.selectList.map(
          (item) => (total = Tools.accAdd(total, item.amount))
        );
      }
      return total;
    },
    invoiceInfoType() {
      for (let i in this.infoList) {
        if (this.infoList[i].id == this.infoId) {
          return {
            issuingType: this.infoList[i].issuingType,
            invoiceType: this.infoList[i].invoiceType,
          };
        }
      }
      return {
        issuingType: null,
        invoiceType: null,
      };
    },
  },
};
</script>

<style lang="scss" scoped>
.listTable-area {
  padding: 30px;
  position: relative;
  left: -30px;
  width: calc(100% + 60px);
  border-top: 20px solid #f3f6fb;
}

.step-item {
  @include size(190px, 36px);
  border-radius: 18px;
  border: 2px solid #b6b0ae;
  // @include bg-setting(null, cover, right);
  color: #b6b0ae;
  text-align: center;
  line-height: 34px;
  font-size: 14px;

  &.b-arrow {
    background: $mainColor;
    color: #fff;
    border: 2px solid $mainColor;
  }
}

.next-icon {
  @include size(18px);
  @include bg-setting("next", 18px 10px, right);
  margin: 0 5px;
}

.name {
  width: 120px;
  color: #000;
  margin-left: 70px;
}
.c-green {
  color: #2f934b;
}
.long-name {
  min-width: 85px;
}
.filter-item {
  padding: 0 10px;
  @include h-c(null, null, #898989, $mainColor);
  cursor: pointer;
  line-height: 15px;
}
.filter-item-active {
  color: $mainColor !important;
}
.b-r {
  border-right: 1px solid #898989;
}
.my-domain-table /deep/ {
  .form-page-bottom-area {
    border: none;
  }
  .ivu-table-wrapper {
    .ivu-table-cell {
      color: #000;
      &:nth-child(1) {
        padding-left: 10px;
        padding-right: 10px;
      }
    }
    .ivu-table-header {
      box-sizing: border-box;
    }
    .ivu-table-row {
      box-sizing: border-box;
      &:hover {
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.15);
        transform: scale(1.01);
      }
    }
  }
  .tab-btn:hover {
    color: $mainColor;
    border-color: $mainColor;
  }
  .tab-btn:focus {
    box-shadow: none;
  }
}
</style>
